package com.example.library.controller;

import com.example.library.entity.BorrowRecord;
import com.example.library.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.library.repository.BorrowRecordRepository;
import com.example.library.repository.BookRepository;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/stats")
public class StatsController {
    @Autowired
    private BorrowRecordRepository borrowRecordRepository;
    @Autowired
    private BookRepository bookRepository;
    @Autowired
    private com.example.library.repository.UserRepository userRepository;

    // 借阅量统计（按月）
    @GetMapping("/borrow-count")
    public Map<String, Object> borrowCount() {
        List<BorrowRecord> records = borrowRecordRepository.findAll();
        Map<String, Long> monthCount = records.stream().filter(r -> r.getBorrowDate() != null)
            .collect(Collectors.groupingBy(r -> r.getBorrowDate().toString().substring(0,7), Collectors.counting()));
        Map<String, Object> res = new HashMap<>();
        res.put("data", monthCount);
        return res;
    }

    // 热门书籍排行榜（按借阅次数，月/周）
    @GetMapping("/hot-books")
    public List<Map<String, Object>> hotBooks(@RequestParam(defaultValue = "month") String type) {
        List<BorrowRecord> records = borrowRecordRepository.findAll();
        Date now = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        if ("week".equals(type)) cal.add(Calendar.DATE, -7); else cal.add(Calendar.MONTH, -1);
        Date from = cal.getTime();
        Map<Book, Long> count = records.stream()
            .filter(r -> r.getBorrowDate() != null && r.getBorrowDate().after(from))
            .collect(Collectors.groupingBy(BorrowRecord::getBook, Collectors.counting()));
        return count.entrySet().stream()
            .sorted((a, b) -> Long.compare(b.getValue(), a.getValue()))
            .limit(10)
            .map(e -> {
                Map<String, Object> map = new HashMap<>();
                map.put("book", e.getKey().getTitle());
                map.put("count", e.getValue());
                return map;
            })
            .collect(Collectors.toList());
    }

    // 读者活跃度分析（饼图）
    @GetMapping("/active-readers")
    public Map<String, Object> activeReaders() {
        List<BorrowRecord> records = borrowRecordRepository.findAll();
        Map<String, Long> readerCount = records.stream().filter(r -> r.getUser() != null)
            .collect(Collectors.groupingBy(r -> r.getUser().getName(), Collectors.counting()));
        Map<String, Object> res = new HashMap<>();
        res.put("data", readerCount);
        return res;
    }

    @GetMapping("/overview")
    public Map<String, Object> overview() {
        Map<String, Object> res = new HashMap<>();
        res.put("books", bookRepository.count());
        res.put("readers", userRepository.findAll().stream().filter(u -> "reader".equals(u.getRole())).count());
        List<BorrowRecord> records = borrowRecordRepository.findAll();
        res.put("borrows", records.size());
        res.put("unreturned", records.stream().filter(r -> r.getReturnDate() == null).count());
        return res;
    }

    @GetMapping("/top-books")
    public List<Map<String, Object>> topBooks() {
        List<BorrowRecord> records = borrowRecordRepository.findAll();
        Map<Book, Long> count = records.stream().filter(r -> r.getBook() != null)
            .collect(Collectors.groupingBy(BorrowRecord::getBook, Collectors.counting()));
        return count.entrySet().stream()
            .sorted((a, b) -> Long.compare(b.getValue(), a.getValue()))
            .limit(10)
            .map(e -> {
                Map<String, Object> map = new HashMap<>();
                map.put("title", e.getKey().getTitle());
                map.put("author", e.getKey().getAuthor());
                map.put("borrowCount", e.getValue());
                return map;
            }).collect(Collectors.toList());
    }

    @GetMapping("/top-readers")
    public List<Map<String, Object>> topReaders() {
        List<BorrowRecord> records = borrowRecordRepository.findAll();
        Map<String, Long> count = records.stream().filter(r -> r.getUser() != null)
            .collect(Collectors.groupingBy(r -> r.getUser().getUsername(), Collectors.counting()));
        Map<String, com.example.library.entity.User> userMap = userRepository.findAll().stream().collect(Collectors.toMap(u -> u.getUsername(), u -> u));
        return count.entrySet().stream()
            .sorted((a, b) -> Long.compare(b.getValue(), a.getValue()))
            .limit(10)
            .map(e -> {
                Map<String, Object> map = new HashMap<>();
                com.example.library.entity.User u = userMap.get(e.getKey());
                map.put("name", u != null ? u.getName() : e.getKey());
                map.put("username", e.getKey());
                map.put("borrowCount", e.getValue());
                return map;
            }).collect(Collectors.toList());
    }
}
